<!-- 预约记录 -->
<template>
  <div id="appointment">
    <!-- 搜索 -->
    <div class="search">
      <myForm v-bind="formConfig" v-model:formData="formData">
        <template #header>
          <Title>
            <template #title>搜索预约记录</template>
          </Title>
        </template>
        <template #footer>
          <div class="footer">
            <el-button type="primary" @click="handleSearch">查询记录</el-button>
          </div>
        </template>
      </myForm>
    </div>
    <!-- 表格 -->
    <div class="table">
      <myTable
        v-bind="tableConfig"
        v-model:pageList="pageList"
        :tableData="tableData"
      >
        <template #header>
          <Title>
            <template #title> 预约记录表单数据 </template>
          </Title>
        </template>
        <template #nowTime="scope">
          {{ convsersionTime(scope.row.time) }}
        </template>
        <template #time="scope">
          {{ convsersionTime(scope.row.startTime, false, 'YYYY-MM-DD') }} -
          {{ convsersionTime(scope.row.endTime, false, 'YYYY-MM-DD') }}
        </template>
        <template #handlerTime="scope">
          <template v-if="scope.row.handlerTime">
            {{ convsersionTime(scope.row.handlerTime) }}
          </template>
          <template v-else> 暂未处理 </template>
        </template>
        <template #handler="scope">
          <template v-if="scope.row.handler">
            {{ scope.row.handler?.name }}
          </template>
          <template v-else-if="scope.row.handler === null">
            该管理员已注销
          </template>
          <template v-else> 暂未处理 </template>
        </template>
        <template #resule="scope">
          <template v-if="scope.row.resule == 0">
            <el-button type="info" plain disabled size="small">
              {{ conversionState(scope.row.resule) }}
            </el-button>
          </template>
          <template v-else-if="scope.row.resule == 1">
            <el-button type="success" plain disabled size="small">
              {{ conversionState(scope.row.resule) }}
            </el-button>
          </template>
          <template v-else-if="scope.row.resule == 2">
            <el-button type="danger" plain disabled size="small">
              {{ conversionState(scope.row.resule) }}
            </el-button>
          </template>
        </template>
        <template #operation="scope">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="通过预约"
            placement="top"
          >
            <el-button
              type="success"
              :icon="Check"
              circle
              @click="handleAppointment(1, scope.row._id)"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="拒绝预约"
            placement="top"
          >
            <el-button
              type="info"
              :icon="Close"
              circle
              @click="handleAppointment(2, scope.row._id)"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除消息"
            placement="top"
          >
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleDelete(scope.row._id)"
            />
          </el-tooltip>
        </template>
      </myTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

import { Title } from '@/components/admin/public'
import myForm from '@/base-ui/form'
import myTable from '@/base-ui/table'

import {
  getSubscribeList,
  handleSchedule,
  deleteSubscribe,
  subscribeList
} from '@/server/serve/api_appointment'

import {
  formConfig,
  tableConfig
} from '@/views/admin/config/apppintment.config'

import convsersionTime from '@/utils/dayjs'
import { conversionState } from '@/utils/conversion'

import { ElMessageBox, ElMessage } from 'element-plus'
import { Check, Delete, Close } from '@element-plus/icons-vue'

// 表单数据
const newTableData: any = {}
for (const item of formConfig.formItems) {
  newTableData[`${item.field}`] = ''
  if (item.field === 'resule') {
    newTableData[`${item.field}`] = 3
  }
}
const formData = ref(newTableData)

// 分页数据
const pageList = ref({
  // 当前页数
  currentPage: 1,
  // 当前页显示数据条数
  pageSize: 10,
  // 条数列表
  pageSizes: [5, 10, 15, 20],
  // 总数
  total: 0
})

// 表格数据
const tableData = ref<any>()

// 监听表格数据展示方式，是否为默认 搜索数据
const defaultDataShowType = ref<boolean>(true)

// 初始化数据
const dataInitialization = () => {
  // 默认数据
  if (defaultDataShowType.value) {
    getSubscribeList(
      pageList.value.pageSize,
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    ).then(({ data }) => {
      tableData.value = data.data?.subscribeList
      pageList.value.total = data.data?.allNums!
    })
  }
  // 搜索数据
  else {
    const { name, phone, email, resule, time } = formData.value
    const startTime = new Date(time[0]).getTime() || 0
    const endTime = new Date(time[1]).getTime() || 0
    subscribeList({
      name,
      phone,
      email,
      resule,
      startTime,
      endTime,
      limit: pageList.value.pageSize,
      skip: (pageList.value.currentPage - 1) * pageList.value.pageSize
    }).then(({ data: searchResult }) => {
      tableData.value = searchResult.data?.subscribeList
      pageList.value.total = searchResult.data?.allNums!
      console.log(searchResult)
    })
  }
}

// 监听分页改变
watch(
  pageList,
  () => {
    dataInitialization()
  },
  { deep: true, immediate: true }
)

// 处理预约进度
/**
 *
 * @param type 1 通过  2 拒绝
 * @param appointmentID 预约消息ID
 */
const handleAppointment = (type: number, appointmentID: string) => {
  if (type === 1) {
    ElMessageBox.confirm('确认要通过该请求吗', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '手滑点错了',
      type: 'warning',
      draggable: true
    })
      .then(async () => {
        const { data: handleResult } = await handleSchedule(appointmentID, 1)
        if (handleResult.code) return ElMessage.warning(handleResult.mes)
        ElMessage({
          type: 'success',
          message: handleResult.mes
        })
        dataInitialization()
      })
      .catch(() => {
        console.log()
      })
  } else if (type === 2) {
    ElMessageBox.confirm('确认要拒绝该请求吗', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '手滑点错了',
      type: 'warning'
    })
      .then(async () => {
        const { data: handleResult } = await handleSchedule(appointmentID, 2)
        if (handleResult.code) return ElMessage.warning(handleResult.mes)
        ElMessage({
          type: 'success',
          message: handleResult.mes
        })
        dataInitialization()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled'
        })
      })
  }
}

// 删除预约记录
/**
 *
 * @param appointmentID 预约消息ID
 */
const handleDelete = (appointmentID: string) => {
  ElMessageBox.confirm('确认删除该预约请求吗', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '手滑点错了',
    type: 'warning',
    draggable: true
  })
    .then(async () => {
      const { data: deleteResult } = await deleteSubscribe(appointmentID)
      if (deleteResult.code) return ElMessage.warning(deleteResult.mes)
      ElMessage({
        type: 'success',
        message: deleteResult.mes
      })
      dataInitialization()
    })
    .catch(() => {
      console.log()
    })
}

// 查询记录
const handleSearch = () => {
  defaultDataShowType.value = false
  dataInitialization()
}
</script>

<style scoped lang="less">
#appointment {
  .search {
    background-color: #fff;
    border-radius: 16px;
    padding: 0 20px 10px;
    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
  .table {
    margin-top: 20px;
    border-radius: 16px;
    padding: 20px;
    background-color: #fff;
  }
}
</style>
